package com.polytech.diploma.DBTablesHelper;

import java.sql.SQLException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.polytech.diploma.SQLGenerator.Oracle.Arguments.DataType;

public class DBTablesHelper {
	private static DBTablesHelper tablesStat = null;
	private Map<String, DBTableFields> tables = null;
	private Database DBConnection;
	
	private DBTablesHelper (Database DBConnection)
	{
		this.tables = new HashMap<String, DBTableFields> ();	
		this.DBConnection = DBConnection;
	}
	
	public static DBTablesHelper getInstance(String schemaName, Database DBConnection)
	{
		if(tablesStat == null)
		{
			tablesStat = new DBTablesHelper(DBConnection);
			tablesStat.fillData(schemaName);
		}
		
		return tablesStat;
	}
	
	private void fillData(String schemaName)
	{
		/*
		 * Connection.getTableList(schemaName);
		 * fill tables with data (key - TableName; value - new TableStatData)
		 */
		String query = 	"SELECT table_name, column_name " +
						"FROM dba_tab_columns " +
						"WHERE owner='" + schemaName + "'";
		try {
			this.DBConnection.connect();
			PreparedStatement pstmt = this.DBConnection.prepareSQL(query);
			ResultSet rs = pstmt.executeQuery();
			while (rs.next()) {
				//TODO: get list of fields for each table
			    tables.put(rs.getString("table_name"), Collections.EMPTY_LIST);
			}
			this.DBConnection.disconnect();
		} catch (KettleDatabaseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	
	public String searchTable(List<String> tableNames, String field)
	{
		for(String tableName: tableNames)
		{
			DBTableFields fields = tables.get(tableName);
			if(fields != null && fields.containsField(field))
				return tableName;
		}
	}
	
	public DataType searchFieldType(String tableName, String field)
	{
		DBTableFields fields = tables.get(tableName);
		if(fields != null && fields.containsField(field))
			return fields.getType(field);
	}

	public int searchFieldPrecision(String tableName, String field) {
		DBTableFields fields = tables.get(tableName);
		if(fields != null && fields.containsField(field))
			return fields.getPrecision(field);
	}
}
